package com.example.base.crash

import android.app.Activity
import android.app.Application
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import com.example.base.R
import java.lang.ref.WeakReference
import java.util.*

/**
 * Created by wanjian on 2018/5/21.
 * 进入安全模式后给所有act添加一个渐变的绿色顶栏
 */
object DebugSafeModeUI {
    private var barHeight = 0
    private val sActivitysWRef: MutableList<WeakReference<Activity>> = ArrayList()
    fun init(application: Application) {
        application.registerActivityLifecycleCallbacks(object :
            ActivityLifecycleCallbacksAdapter() {
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
                super.onActivityCreated(activity, savedInstanceState)
                sActivitysWRef.add(WeakReference(activity))
                if (Cockroach.isSafeMode) {
                    //进入安全模式后给新创建的act添加渐变绿色顶栏
                    enterSafeMode(activity)
                }
            }

            override fun onActivityDestroyed(activity: Activity) {
                super.onActivityDestroyed(activity)
                for (reference in sActivitysWRef) {
                    val act = reference.get()
                    if (act === activity) {
                        sActivitysWRef.remove(reference)
                        return
                    }
                }
            }
        })
        barHeight = (application.resources.displayMetrics.density * 50).toInt()
    }

    /**
     * 进入安全模式后给当前已存在的act添加渐变绿色顶栏
     */
    fun showSafeModeUI() {
        for (reference in sActivitysWRef) {
            val activity = reference.get()
            if (activity == null || activity.isFinishing) {
                continue
            }
            enterSafeMode(activity)
        }
    }

    fun enterSafeMode(activity: Activity) {
        try {
            val view = View(activity)
            val params = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, barHeight)
            view.layoutParams = params
            view.setBackgroundResource(R.drawable.safe_mode_drawable)
            (activity.window.decorView as ViewGroup).addView(view)
        } catch (throwable: Throwable) {
            throwable.printStackTrace()
        }
    }
}